<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
    <style>
        .laytable-cell-customization {
            text-align: center;
            height: auto !important;
            white-space: normal;
            overflow: visible;
            text-overflow: inherit;
            word-break: break-all;
        }

        .layui-btn-custom {
            background: 0 0;
            color: #ff0004;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">企业编号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="enterpriseNo" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">企业名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="enterpriseName" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">创建时间</label>
                            <div class="layui-input-inline">
                                <input type="text" name="dateRange" id="dateRange" autocomplete="off"
                                       class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">更新时间</label>
                            <div class="layui-input-inline">
                                <input type="text" name="updateDateRange" id="updateDateRange" autocomplete="off"
                                       class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-sm layui-btn-normal data-add-btn" lay-event="add">新增</button>
                <button class="layui-btn layui-btn-sm layui-btn data-delete-btn" lay-event="import">导入</button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete">删除</button>
                <button class="layui-btn layui-btn-sm layui-btn data-delete-btn" lay-event="top">推荐</button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="cancelTop">取消推荐</button>
                <div style="display: block; float: right;margin-right: 20px">
                    <button class="layui-btn layui-btn-custom layui-btn-sm data-add-btn text-show-btn" onclick="getTopList()">
                        <label id="top_num" style="color:#ff0004;"></label>
                    </button>
                </div>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
        <script type="text/html" id="currentTableBar">
            <div class="layui-inline">
                <a class="layui-btn layui-btn-warm layui-btn-sm" lay-event="showTransferCode">授权码</a>
            </div>
        </script>

        <script type="text/html" id="imgTemp">
            <img src="{{d.avatar}}" style="width: 100%;height: 45px;"/>
        </script>
    </div>
</div>
<script src="../../lib/common/common.js" charset="utf-8"></script>
<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script>
    let myClos;
    let getTopTag = true;
    layui.use(['form', 'table', 'laydate'], function () {
        var $ = layui.jquery,
            form = layui.form,
            laydate = layui.laydate,
            table = layui.table;

        //执行一个laydate实例
        laydate.render({
            elem: '#dateRange', //指定元素
            max: 0, // 限制最大值为当前日期
            type: 'date',
            range: true, //开启范围选择
        });//执行一个laydate实例

        laydate.render({
            elem: '#updateDateRange', //指定元素
            max: 0, // 限制最大值为当前日期
            type: 'date',
            range: true, //开启范围选择
        });

        table.render({
            elem: '#currentTableId',
            url: '/enterprise/page/list',
            method: 'POST',
            contentType: 'application/json',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {type: "checkbox", fixed: 'left', style: 'height:60px;'},
                {
                    field: 'numbering', title: '序号', width: 60, align: 'center', templet: function (d) {
                        return d.LAY_INDEX; //返回序号
                    }
                },
                {
                    field: 'avatar', title: '头像', align: 'center', minWidth: 80, templet: '#imgTemp',
                    style: 'height:60px;',
                },
                {field: 'createTime', title: '创建时间', sort: true, align: 'center', minWidth: 120},
                {field: 'updateTime', title: '更新时间', sort: true, align: 'center', minWidth: 120},
                {field: 'enterpriseNo', title: '企业编号', align: 'center', minWidth: 120},
                {field: 'enterpriseName', title: '企业名称', align: 'center', minWidth: 120},
                {field: 'organizationCode', title: '统一社会信用代码', align: 'center', minWidth: 120},
                {field: 'registrationType', title: '企业类型', align: 'center', minWidth: 120},
                {field: 'industry', title: '所属行业', align: 'center', minWidth: 120},
                {
                    field: 'region', title: '所属地区', align: 'center', minWidth: 120, templet: function (d) {
                        if (isNotNull(d.province) && isNotNull(d.city) && isNotNull(d.area)) {
                            return d.province + "-" + d?.city + "-" + d.area
                        }
                        return ""
                    }
                },
                {field: 'establishmentDate', title: '成立时间', sort: true, align: 'center', minWidth: 120},
                {field: 'legalPerson', title: '法定代表人', align: 'center', minWidth: 120},
                {field: 'phoneNumber', title: '联系电话', align: 'center', minWidth: 120},
                {field: 'email', title: '电子邮箱', align: 'center', minWidth: 120},
                {field: 'userId', title: '管理员ID', align: 'center', minWidth: 120},
                {
                    field: 'nickName', title: '管理员昵称', align: 'center', minWidth: 120, templet: function (d) {
                        if (isNotNull(d.nickName)) {
                            return d.nickName
                        }
                        return d.enterpriseName
                    }
                },
                {
                    title: '操作',
                    fixed: 'right',
                    toolbar: '#currentTableBar',
                    width: 100,
                    align: 'center',
                    style: 'height:60px;'
                }
            ]],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 50,
            page: true,
            request: {
                pageName: 'pageNum',
                limitName: 'pageSize'
            },
            response: { //定义后端 json 格式，详细参见官方文档
                statusName: 'code', //状态字段名称
                statusCode: '200', //状态字段成功值
                msgName: 'msg', //消息字段
                countName: 'total', //总数字段
                dataName: 'rows' //数据字段
            },
            done: function (res, curr, count) {//表格渲染完成的回调函数
                // 给指定的列加上css样式
                let colsList = this.cols[0];
                myClos = colsList;
                for (let cols of colsList) {
                    if (cols.field === 'avatar' || cols.title === '操作') {
                        // 添加样式
                        let classStr = ".laytable-cell-1-" + cols.key;
                        $(classStr).addClass('laytable-cell-customization')//
                    }
                }

                // 统计推荐的企业总数
                let rows = table.getData("currentTableId");
                let top_num = 0;
                rows.forEach(data => {
                    if(data.enterpriseTop > 0){
                        top_num++;
                    }
                });
                $("#top_num").text("查看推荐企业(" + top_num + ")");
            }
        });

        // 监听表格排序事件
        table.on('sort(currentTableFilter)', function (obj) {
            for (let cols of myClos) {
                if (cols.field === 'avatar' || cols.title === '操作') {
                    // 添加样式
                    let classStr = ".laytable-cell-1-" + cols.key;
                    $(classStr).addClass('laytable-cell-customization')//
                }
            }
        });

        // 监听表格双击事件
        table.on('rowDouble(currentTableFilter)', function (obj) {
            const data = obj.data;
            const index = layer.open({
                title: '企业详情',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                area: ['100%', '100%'],
                content: './edit.html?userId=' + data.userId,
            });
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            let dataRangeList = data.field.dateRange.split(` - `)
            let dataRange = {}
            if (dataRangeList.length === 2) {
                dataRange = {
                    'startDate': dataRangeList[0],
                    'endDate': dataRangeList[1]
                }
            }
            data.field.dateRange = JSON.stringify(dataRange);
            let updateDateRangeList = data.field.updateDateRange.split(` - `)
            let updateDateRange = {}
            if (updateDateRangeList.length === 2) {
                updateDateRange = {
                    'startDate': updateDateRangeList[0],
                    'endDate': updateDateRangeList[1]
                }
            }
            data.field.updateDateRange = JSON.stringify(updateDateRange);
            //执行搜索重载
            table.reload('currentTableId', {
                page: {
                    curr: 1
                }
                , where: data.field
            }, 'data');

            return false;
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                layer.open({
                    title: '添加企业',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    content: './add.html',
                });
            }
            if (obj.event === 'delete') {  // 监听删除操作
                const checkStatus = table.checkStatus('currentTableId');
                const data = checkStatus.data;
                if (data.length > 0) {
                    layer.confirm('确定删除吗?', function (index) {
                        const removeList = data.filter(d => d.transferStatus === '0').map(d => d.userId);
                        const successList = data.filter(d => d.transferStatus === '0').map(d => d.enterpriseName);
                        const failureList = data.filter(d => d.transferStatus === '1').map(d => d.enterpriseName);
                        if (failureList.length > 0) {
                            const failureMessage = `以下企业已转移，不可删除！<br/>${failureList.map((name, index) => `${index + 1}、${name}<br/>`).join('')}`;
                            layer.msg(failureMessage, {icon: 5});
                            return;
                        }
                        if (removeList.length > 0) {
                            const successMessage = `${successList.map(name => `、${name}`).join('')}已删除`;
                            layer.load();
                            $.ajax({
                                type: 'POST',
                                url: '/enterprise/delete',
                                data: JSON.stringify(removeList),
                                dataType: 'json',
                                contentType: 'application/json',
                                success: function (req) {
                                    if (req.code === '200') {
                                        layer.msg(successMessage, {icon: 1});
                                        reloadTable();
                                    } else {
                                        layer.msg('删除失败', {icon: 5});
                                    }
                                    layer.closeAll('loading');
                                },
                                error: function (e) {
                                    layer.msg('请求错误，请稍后再试', {icon: 5});
                                    layer.closeAll('loading');
                                }
                            });
                        } else {
                            layer.msg('请选择要删除的企业', {icon: 5});
                        }
                        layer.close(index);
                    });
                } else {
                    layer.msg('请至少选中一行数据', {icon: 5});
                }
            }
            if (obj.event === 'import') {
                let param = {
                    actions: 'ENTERPRISE_IMPORT'
                }
                layer.open({
                    type: 2,
                    title: "企业数据导入",
                    content: '../common/import/importComponents.html',
                    area: ['274px', '140px'],
                    success: function (layero, index) {
                        // 获取子页面的iframe
                        var iframe = window['layui-layer-iframe' + index];
                        // 向子页面的全局函数child传参
                        let data = {
                            module: 'ENTERPRISE_IMPORT',
                            param: param,
                            templateName: '企业数据导入模板.xlsx',
                            dataPreviewUrl: '../common/import/dataPreviewTable.html',
                            errTemplateName: '企业数据导入失败.xlsx',
                            errDataFile: {
                                id: "企业名称",
                                errMsg: "错误信息"
                            }
                        }
                        iframe.childParam(data);
                    }
                });
            }
            if (obj.event === 'top') {  // 监听推荐操作

                let checkStatus = table.checkStatus('currentTableId')
                    , rows = checkStatus.data;
                if (rows.length === 0) {
                    layer.alert('至少选中一行数据');
                    return;
                } else if(rows.length > 1){
                    layer.alert('每次只能选择一个企业推荐！');
                    return;
                }
                let data = rows[0];
                if(data.enterpriseTop > 0){
                    layer.alert('企业已推荐！');
                    return;
                }
                layer.confirm('确定推荐所选择的企业吗', function (index) {
                    $.ajax({
                        type: 'GET',
                        url: '/enterprise/top/' + data.userId,
                        data: {},
                        dataType: 'json',
                        success: function (req) {
                            if (req.code == 200) {
                                layer.msg("已推荐");
                                reloadTable();
                            } else {
                                layer.msg(req.msg);
                            }
                            layer.close(index);
                        },
                        error: function (e) {
                            layer.msg("出错啦");
                            layer.close(index);
                        }
                    })
                });
            }
            if (obj.event === 'cancelTop') {  // 监听取消推荐操作

                let checkStatus = table.checkStatus('currentTableId')
                    , rows = checkStatus.data;
                if (rows.length === 0) {
                    layer.alert('至少选中一行数据');
                    return;
                } else if(rows.length > 1){
                    layer.alert('每次只能选择一个企业推荐！');
                    return;
                }
                let data = rows[0];
                if(!(data.enterpriseTop > 0)){
                    layer.alert('企业已取消推荐！');
                    return;
                }
                layer.confirm('确定取消推荐所选择的企业吗', function (index) {
                    $.ajax({
                        type: 'GET',
                        url: '/enterprise/top/cancel/' + data.userId,
                        data: {},
                        dataType: 'json',
                        success: function (req) {
                            if (req.code == 200) {
                                layer.msg("已取消推荐");
                                reloadTable();
                            } else {
                                layer.msg(req.msg);
                            }
                            layer.close(index);
                        },
                        error: function (e) {
                            layer.msg("出错啦");
                            layer.close(index);
                        }
                    })
                });
            }
        });
        table.on('tool(currentTableFilter)', function (obj) {
            if (obj.event === 'showTransferCode') {
                const data = obj.data;
                layui.use(['layer'], function () {
                    let layer = layui.layer;
                    let loading = layer.msg("加载中...", {
                        icon: 16,
                        time: -1
                    })
                    let param = {
                        userId: data.userId,
                    }
                    $.ajax({
                        url: '/enterprise/qr/code',
                        type: 'post',
                        data: JSON.stringify(param),
                        xhrFields: {
                            withCredentials: true
                        },
                        dataType: 'json',
                        contentType: 'application/json; charset=UTF-8',
                        success: function (res) {
                            layer.close(loading);
                            let html = "<div style='text-align: center;padding-top: 10px;'>" +
                                "<img style='height: 250px;width: 250px;' src='" + res.cosUrl + "?t=" + Math.random() + "'>" +
                                "</div>" +
                                "<div style='padding-top: 20px;text-align: center;'>请使用微信扫码进行绑定</div>";
                            layer.open({
                                type: 1,
                                title: '授权转移码',
                                area: ['300px', '420px'],
                                shade: 0,
                                shadeClose: true,
                                content: html,
                                btn: ['下载图片', '取消'],
                                btn1: function (index) {
                                    let a = document.createElement('a');
                                    let event = new MouseEvent('click');
                                    a.download = "分享注册码";
                                    a.href = res.cosUrl;
                                    a.dispatchEvent(event);
                                },
                                btn2: function (index) {
                                    layer.close(index);
                                }
                            });
                            layer.close(loading);
                        },
                        error: function (e) {
                            layer.close(loading);
                            layer.msg('出错啦！');
                            setTimeout(function () {
                                layer.closeAll();
                            }, 2000)
                        }
                    });
                })

            }
        })

        // 监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
            console.log(obj)
        });

    });

    /**
     * 重载表格数据
     */
    function reloadTable() {
        let top_num = 0;
        layui.use(['table'], function () {
            let table = layui.table;
            table.reload('currentTableId', {
                url: '/enterprise/page/list'
            });
            // 统计推荐的企业总数
            let rows = table.getData("currentTableId");
            rows.forEach(data => {
                if(data.enterpriseTop > 0){
                    top_num++;
                }
            });
        });
        $("#top_num").text("查看推荐企业(" + top_num + ")");
    }

    /**
     * 查看推荐企业
     */
    function getTopList(){
        getTopTag = !getTopTag;
        if(getTopTag){
            reloadTable();
        } else {
            let top_num = 0;
            layui.use(['table'], function () {
                let table = layui.table;
                table.reload('currentTableId', {
                    url: '/enterprise/page/top/list'
                });
                top_num = table.getData("currentTableId").length;
            });
            $("#top_num").text("查看推荐企业(" + top_num + ")");
        }
    }

</script>

</body>
</html>
